/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。
 * 
 * 欢迎到知启蒙网站（https://www.zhiqim.com）购买正版软件，知启蒙还提供许多开源框架和软件。
 * 
 * 1、本软件产品所有源代码受《中华人民共和国著作权法》和其他有关法律、法规的保护，其所有知识产权归湖南知启蒙科技有限公司所有；
 * 2、禁止复制和修改。不得复制修改、翻译或改编本软件所有源代码，或者基于本软件产品创作衍生作品；
 * 3、禁止进行逆向工程。不得对本软件的源代码进行逆向工程、反编译或试图以其他方式发现软件的源代码；
 * 4、个别授权：如需进行商业性的销售、复制、分发，包括但不限于软件销售、预装、捆绑等，必须获得知启蒙的书面授权和许可；
 * 5、保留权利：本注释未明示授权的其他一切权利仍归知启蒙所有，任何人使用其他权利时必须获得知启蒙的书面同意。
*/
package net.redxyz.repost.resource.presenter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.ZmlContexts;
import org.zhiqim.httpd.context.annotation.AnIntercept;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.annotation.AnFilterNot;
import org.zhiqim.kernel.extend.HashMapSO;
import org.zhiqim.kernel.extend.MapSO;
import org.zhiqim.kernel.paging.PageResult;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.dbo.Selector;
import org.zhiqim.orm.dbo.Updater;

import net.redxyz.repost.resource.model.ItemDelistInfo;
import net.redxyz.repost.resource.model.SellerCatFirst;
import net.redxyz.repost.resource.model.SellerCatRoot;
import net.redxyz.repost.resource.model.SellerCatSecond;
import net.redxyz.top.repost.dbo.AssRepostPlan;
import net.redxyz.top.repost.dbo.AssRepostPlanDetail;

@AnAlias("RepostPresenter")
public class RepostPresenter
{
    /** 自动上架添加时获取分类字符串 */
    public static String getItemScriptStrByAdd(SellerCatRoot seRoot)
    {
        StringBuffer strb = new StringBuffer();
        strb.append("<table class=\"z-table z-bg-white z-pd3 z-nowrap zi-bd-b z-w100p\"><tr class=\"z-h40\">").append("\r\n");
        strb.append("<td align=\"left\">&nbsp;");
        strb.append("<input id='hall' class=\"z-input z-mg-r6 z-h22\" type=checkbox onclick='javascript:SelectAll(this.form, this.checked);' name=planSellerCids value='' checked>");
        strb.append("全部分类");
        strb.append("</td>");
        strb.append("</tr></table>").append("\r\n");

        strb.append("<table class=\"z-table z-bg-white z-pd-l3 z-mg-t6 z-nowrap\"><tr class=\"z-h22\">").append("\r\n");
        strb.append("<td align=\"left\">&nbsp;");
        strb.append("<input id='0' type=checkbox class=\"z-input z-mg-r6 z-h22\" onclick='javascript:SelectChkBox(this.form, this.checked, this.id);' name=planSellerCids value="
            + seRoot.getCid() + ">");
        strb.append("指定以下所有分类");
        strb.append("</td>");
        strb.append("</tr></table>").append("\r\n");

        for (int i = 0; i < seRoot.size(); i++)
        {
            SellerCatFirst first = seRoot.get(i);
            boolean isPLast = (i == seRoot.size() - 1);
            boolean hasSecond = first.size() > 0;

            String firstIco = isPLast ? (hasSecond ? "z-mlastnode" : "z-lastnode") : (hasSecond ? "z-mnode" : "z-node");
            strb.append("<table class=\"z-table z-bg-white z-pd-l3 z-nowrap\"><tr class=\"z-h22\">");
            strb.append("<td width=* align=left nowrap=nowrap>");
            if (hasSecond)
                strb.append("<a href=\"javascript:treeExpand('" + first.getCid() + "')\"><i id=\"ico-" + first.getCid() + "\" class=\"z-ico z-tree z-normal "
                    + firstIco + "\"></i></a>");
            else
                strb.append("<i id=\"ico-" + first.getCid() + "\" class=\"z-ico z-tree z-normal " + firstIco + "\"></i>");
            if (hasSecond)
                strb.append("&nbsp;" + first.getName() + "</td>");
            else
                strb.append("&nbsp;<input type=checkbox class=\"z-input z-mg-r6 z-h22\" id='0-" + first.getCid()
                    + "' onclick='javascript:SelectChkBox(this.form, this.checked, this.id);' name=planSellerCids value=" + first.getCid() + ">"
                    + first.getName() + "</td>");

            strb.append("</tr></table>").append("\r\n");

            if (hasSecond)
            {
                strb.append("\t<table id=\"menu-"
                    + first.getCid()
                    + "\" class=\"z-table z-bg-white z-pd-l3\" style=\"display:'none';line-height:20px;\" width=100% align=center border=0 cellspacing=0 cellpadding=0 bgcolor=#2A689D><tr align=center height=22 bgcolor=#fff><td>");
                for (int j = 0; j < first.size(); j++)
                {
                    SellerCatSecond second = first.get(j);

                    String secondIco = (j == first.size() - 1) ? "z-lastnode" : "z-node";
                    strb.append("\t\t<table class=\"z-table z-bg-white\"><tr class=\"z-h22\">").append("\r\n");
                    strb.append("\t\t\t<td width=* align=left nowrap=nowrap>");
                    if (!isPLast)
                        strb.append("<i class=\"z-ico z-tree z-normal z-vertline\"></i>");
                    else
                        strb.append("<i class=\"z-ico z-tree z-normal z-blank\"></i>");
                    strb.append(
                        "<i id=\"ico-"
                            + second.getCid()
                            + "\" class=\"z-ico z-tree z-normal "
                            + secondIco
                            + "\"></i>&nbsp;<input id='0-"
                            + first.getCid()
                            + "_"
                            + second.getCid()
                            + "' type=checkbox class=\"z-input z-mg-r6 z-h22\" onclick='javascript:SelectChkBox(this.form, this.checked, this.id);' name=planSellerCids value="
                            + second.getCid() + ">" + second.getName() + "</td>").append("\r\n");
                    strb.append("\t\t</tr></table>").append("\r\n");
                }

                strb.append("\t</td></tr></table>").append("\r\n");
            }
        }

        return strb.toString();
    }

    /** 自动上架修改时获取分类字符串 */
    public static String getItemScriptStrByModify(SellerCatRoot seRoot, String sellerCids)
    {
        StringBuffer strb = new StringBuffer();
        strb.append("<table class=\"z-table z-bg-white z-pd-l3 z-nowrap zi-bd-b\"><tr class=\"z-h40\">").append("\r\n");
        strb.append("<td align=\"left\">&nbsp;");
        if (Validates.isEmpty(sellerCids))
            strb.append("<input id='hall' type=checkbox class=\"z-input z-mg-r6 z-h22\" onclick='javascript:SelectAll(this.form, this.checked);' name=planSellerCids value='' checked disabled>");
        else
            strb.append("<input id='hall' type=checkbox class=\"z-input z-mg-r6 z-h22\" onclick='javascript:SelectAll(this.form, this.checked);' name=planSellerCids value='' disabled>");
        strb.append("全部分类");
        strb.append("</td>");
        strb.append("</tr></table>").append("\r\n");

        strb.append("<table class=\"z-table z-bg-white z-pd-l3 z-mg-t6 z-nowrap\"><tr style=\"height:22px;\">").append("\r\n");
        strb.append("<td align=\"left\">&nbsp;");
        if (Validates.isNotEmpty(sellerCids) && sellerCids.startsWith("0"))
            strb.append("<input id='0' type=checkbox class=\"z-input z-mg-r6 z-h22\" onclick='javascript:SelectChkBox(this.form, this.checked, this.id);' name=planSellerCids value="
                + seRoot.getCid() + " checked disabled>");
        else
            strb.append("<input id='0' type=checkbox class=\"z-input z-mg-r6 z-h22\" onclick='javascript:SelectChkBox(this.form, this.checked, this.id);' name=planSellerCids value="
                + seRoot.getCid() + " disabled>");
        strb.append("指定以下所有分类");
        strb.append("</td>");
        strb.append("</tr></table>").append("\r\n");

        for (int i = 0; i < seRoot.size(); i++)
        {
            SellerCatFirst first = seRoot.get(i);
            boolean isPLast = (i == seRoot.size() - 1);
            boolean hasSecond = first.size() > 0;

            String firstIco = isPLast ? (hasSecond ? "z-mlastnode" : "z-lastnode") : (hasSecond ? "z-mnode" : "z-node");
            strb.append("<table class=\"z-table z-bg-white z-pd-l3 z-nowrap\"><tr class=\"z-h22\">");
            strb.append("<td width=* align=left nowrap=nowrap>");
            if (hasSecond)
                strb.append("<a href=\"javascript:treeExpand('" + first.getCid() + "')\"><i id=ico-" + first.getCid() + " class=\"z-ico z-tree z-normal "
                    + firstIco + "\"></i></a>");
            else
                strb.append("<i id=\"ico-" + first.getCid() + "\" class=\"z-ico z-tree z-normal " + firstIco + "\"></i>");
            if (hasSecond)
                strb.append("&nbsp;" + first.getName() + "</td>");
            else
            {
                if (Validates.isNotEmpty(sellerCids) && sellerCids.contains(String.valueOf(first.getCid())))
                    strb.append("&nbsp;<input type=checkbox id='0-"
                        + first.getCid()
                        + "' class=\"z-input z-mg-r6 z-h22\" onclick='javascript:SelectChkBox(this.form, this.checked, this.id);' checked disabled name=planSellerCids value="
                        + first.getCid() + ">" + first.getName() + "</td>");
                else
                    strb.append("&nbsp;<input type=checkbox id='0-"
                        + first.getCid()
                        + "' class=\"z-input z-mg-r6 z-h22\" onclick='javascript:SelectChkBox(this.form, this.checked, this.id);' disabled name=planSellerCids value="
                        + first.getCid() + ">" + first.getName() + "</td>");
            }
            strb.append("</tr></table>").append("\r\n");

            if (hasSecond)
            {
                strb.append("\t<table id='menu-" + first.getCid()
                    + "' class=\"z-table z-bg-white z-pd-l3\" style=\"display:'none';line-height:20px;\"><tr class=\"z-h22\"><td>");
                for (int j = 0; j < first.size(); j++)
                {
                    SellerCatSecond second = first.get(j);

                    String secondIco = (j == first.size() - 1) ? "z-lastnode" : "z-node";
                    strb.append("\t\t<table class=\"z-table z-bg-white z-nowrap\"><tr class=\"z-h22\">").append("\r\n");
                    strb.append("\t\t\t<td width=* align=left nowrap=nowrap>");
                    if (!isPLast)
                        strb.append("<i class=\"z-ico z-tree z-normal z-vertline\"></i>");
                    else
                        strb.append("<i class=\"z-ico z-tree z-normal z-blank\"></i>");
                    if (Validates.isNotEmpty(sellerCids) && sellerCids.contains(String.valueOf(second.getCid())))
                        strb.append(
                            "<i id=\"ico-"
                                + second.getCid()
                                + "\" class=\"z-ico z-tree z-normal "
                                + secondIco
                                + "\"></i><input id='0-"
                                + first.getCid()
                                + "_"
                                + second.getCid()
                                + "' type=checkbox class=\"z-input z-mg-r6 z-h22\" onclick='javascript:SelectChkBox(this.form, this.checked, this.id);' checked disabled name=planSellerCids value="
                                + second.getCid() + ">" + second.getName() + "</td>").append("\r\n");
                    else
                        strb.append(
                            "<i id=\"ico-"
                                + second.getCid()
                                + "\" class=\"z-ico z-tree z-normal "
                                + secondIco
                                + "\"></i><input id='0-"
                                + first.getCid()
                                + "_"
                                + second.getCid()
                                + "' type=checkbox class=\"z-input z-mg-r6 z-h22\" onclick='javascript:SelectChkBox(this.form, this.checked, this.id);' disabled name=planSellerCids value="
                                + second.getCid() + ">" + second.getName() + "</td>").append("\r\n");
                    strb.append("\t\t</tr></table>").append("\r\n");
                }

                strb.append("\t</td></tr></table>").append("\r\n");
            }
        }

        return strb.toString();
    }

    /**
     * 排除计划宝贝
     * @param request 请求
     * @param planId 计划编号
     * @param numIid 宝贝编号
     * @throws Exception
     */
    @AnIntercept("chkAjax")
    public static void doDeleteDetail(HttpRequest request, String planId, long numIid) throws Exception
    {
        // 更新排除字段
        AssRepostPlan plan = ORM.table().item(AssRepostPlan.class, planId);
        if (plan == null)
        {
            request.setResponseError("该上下架计划已删除，请重建");
            return;
        }

        Selector selector = new Selector();
        selector.addMust("planId", planId);
        selector.addMust("numIid", numIid);
        selector.addMaybeNotEqual("itemStatus", 2);// 排除的除外
        selector.addReplace("d", "001");
        AssRepostPlanDetail detail = ORM.table().item(AssRepostPlanDetail.class, selector);
        if (detail == null)
        {
            request.setResponseError("该宝贝不在计划中或已排除");
            return;
        }

        String planDownIids = plan.getPlanDownIids();// 手动排除的字段
        if (Validates.isEmpty(planDownIids))
            planDownIids = detail.getItemSequence() + "";
        else
            planDownIids += "," + detail.getItemSequence();

        plan.setPlanDownIids(planDownIids);
        ORM.table().update(plan);

        Updater updater = new Updater();
        updater.addMaybe("planId", planId);
        updater.addMaybe("numIid", numIid);
        updater.addField("itemStatus", 2);
        updater.addField("operateStatus", 3);
        updater.addReplace("d", "001");

        ORM.table().update(AssRepostPlanDetail.class, updater);
        request.setResponseResult("排除成功");
    }

    /**
     * 取消排除详情
     * @param request 请求
     * @param planId 计划编号
     * @param numIid 宝贝编号
     * @throws Exception
     */
    @AnIntercept("chkAjax")
    public static void doCancelDeleteDetail(HttpRequest request, String planId, long numIid) throws Exception
    {
        // 更新排除字段
        AssRepostPlan plan = ORM.table().item(AssRepostPlan.class, planId);
        if (plan == null)
        {
            request.setResponseError("该上下架计划已删除，请重建");
            return;
        }

        String planDownIids = plan.getPlanDownIids();// 手动排除的字段
        String[] iids = planDownIids.split(",");

        StringBuffer strb = new StringBuffer();
        for (int i = 0; i < iids.length; i++)
        {
            String s = iids[i];
            if (Validates.isEmpty(s) || s.equals(String.valueOf(numIid)))
                continue;

            strb.append(",").append(s);
        }

        String newIds = strb.toString();
        if (newIds.startsWith(","))
            newIds = newIds.substring(1);

        plan.setPlanDownIids(newIds);
        ORM.table().update(plan);

        Updater updater = new Updater();
        updater.addMaybe("planId", planId);
        updater.addMaybe("numIid", numIid);
        updater.addField("itemStatus", 0);
        updater.addField("operateStatus", 0);
        updater.addReplace("d", "001");

        ORM.table().update(AssRepostPlanDetail.class, updater);
        request.setResponseResult("取消排除成功");
    }

    /** 查询计划详情 */
    @AnIntercept("chkAjax")
    @AnFilterNot
    public static String doQueryPlanDetail(HttpRequest request, String planId, String itemTitle, int planWeek, int itemStatus, int operateStatus, int page)
        throws Exception
    {
        int pageSize = 10;

        Selector selector = new Selector();
        selector.addMaybe("planId", planId);
        selector.addMaybeLike("itemTitle", itemTitle);
        selector.addMaybe("planWeek", planWeek);
        if (itemStatus == -1)// 全部时排除不查
            selector.addMaybeNotEqual("itemStatus", 2);
        else
            selector.addMaybe("itemStatus", itemStatus);

        selector.addMaybe("operateStatus", operateStatus);
        selector.addOrderbyAsc("planWeek");
        selector.addOrderbyAsc("planTime");
        selector.addReplace("d", "001");

        PageResult<AssRepostPlanDetail> result = ORM.table().page(AssRepostPlanDetail.class, page, pageSize, selector);
        MapSO attrMap = new HashMapSO();
        attrMap.put("result", result);
        attrMap.put("planWeek", planWeek);
        attrMap.put("itemStatus", itemStatus);
        attrMap.put("operateStatus", operateStatus);
        attrMap.put("itemTitle", itemTitle);

        String ftlPath = "/zview/plan/presenter/repostPlanDetail.zml";
        String ret = ZmlContexts.parseZmlPath(request, ftlPath, attrMap);
        return ret;
    }

    /** 查询计划分布 */
    @AnIntercept("chkAjax")
    public static String doQueryPlanDistr(HttpRequest request, String planId) throws Exception
    {
        AssRepostPlan plan = ORM.table().item(AssRepostPlan.class, planId);
        String[] hours = plan.getPlanHours().split(",");
        String[] weeks = plan.getPlanWeeks().split(",");

        Map<String, ItemDelistInfo> result = new TreeMap<String, ItemDelistInfo>();
        List<ItemDelistInfo> itemDelistList = new ArrayList<ItemDelistInfo>();

        ItemDelistInfo totalIdInfo = new ItemDelistInfo("总计");
        totalIdInfo.setTotalAll(0);

        Selector selector = new Selector();
        selector.addMaybe("planId", planId);
        selector.addReplace("d", "001");
        List<AssRepostPlanDetail> detailList = ORM.table().list(AssRepostPlanDetail.class, selector);

        for (String hour : hours)
        {
            ItemDelistInfo delistInfo = new ItemDelistInfo(hour);
            delistInfo.setHour(hour);

            for (String week : weeks)
            {
                int num = getNum(detailList, week, hour);

                int w = Integer.parseInt(week);
                switch (w)
                {
                case 1:
                    delistInfo.setMon(num);
                    break;
                case 2:
                    delistInfo.setTue(num);
                    break;
                case 3:
                    delistInfo.setWed(num);
                    break;
                case 4:
                    delistInfo.setThu(num);
                    break;
                case 5:
                    delistInfo.setFir(num);
                    break;
                case 6:
                    delistInfo.setSat(num);
                    break;
                case 7:
                    delistInfo.setSun(num);
                    break;
                }
            }

            itemDelistList.add(delistInfo);
            result.put(hour, delistInfo);
        }

        for (ItemDelistInfo idInfo : itemDelistList)
        {
            totalIdInfo.setMon(totalIdInfo.getMon() + idInfo.getMon());
            totalIdInfo.setTue(totalIdInfo.getTue() + idInfo.getTue());
            totalIdInfo.setWed(totalIdInfo.getWed() + idInfo.getWed());
            totalIdInfo.setThu(totalIdInfo.getThu() + idInfo.getThu());
            totalIdInfo.setFir(totalIdInfo.getFir() + idInfo.getFir());
            totalIdInfo.setSat(totalIdInfo.getSat() + idInfo.getSat());
            totalIdInfo.setSun(totalIdInfo.getSun() + idInfo.getSun());
        }
        result.put("99", totalIdInfo);

        MapSO attrMap = new HashMapSO();
        attrMap.put("result", result);

        String ftlPath = "/zview/plan/presenter/repostPlanDistr.zml";
        String ret = ZmlContexts.parseZmlPath(request, ftlPath, attrMap);
        return ret;
    }

    private static int getNum(List<AssRepostPlanDetail> detailList, String week, String hour)
    {
        int num = 0;
        int planWeek = Integer.parseInt(week);
        for (AssRepostPlanDetail detail : detailList)
        {
            String planTime = detail.getPlanTime();
            String beginTime = hour + ":00:00";
            String endTime = hour + ":59:59";
            if (detail.getPlanWeek() == planWeek && planTime.compareTo(beginTime) >= 0 && planTime.compareTo(endTime) <= 0)
                num++;
        }

        return num;
    }
}
